package org.ciallo.simplemusicplayer.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputLayout;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.adapter.PlaylistManagementAdapter;
import org.ciallo.simplemusicplayer.data.model.PlaylistInfo;
import org.ciallo.simplemusicplayer.util.Constants;
import org.ciallo.simplemusicplayer.viewmodel.PlaylistViewModel;
import timber.log.Timber;

import java.util.ArrayList;


import static java.security.AccessController.getContext;

/**
 * @author Jukomu
 * @Description: 歌单管理Activity，用于显示、创建、编辑和删除用户的歌单
 * @Package: org.ciallo.simplemusicplayer.activity
 * @Project: SimpleMusicPlayer
 * @name: PlaylistManagementActivity
 * @Date: 2025/5/30-03:25
 * @Filename: PlaylistManagementActivity
 */
public class PlaylistManagementActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private RecyclerView recyclerViewPlaylists;
    private PlaylistManagementAdapter adapter;
    private TextView tvEmptyPlaylists;
    private FloatingActionButton fabCreatePlaylist;
    private PlaylistViewModel playlistViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playlist_management);

        toolbar = findViewById(R.id.toolbar_playlist_management_activity);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("歌单管理");
        }

        recyclerViewPlaylists = findViewById(R.id.recyclerView_playlist_management_list);
        tvEmptyPlaylists = findViewById(R.id.textView_empty_playlist_management);
        fabCreatePlaylist = findViewById(R.id.fab_playlist_management_create);

        playlistViewModel = new ViewModelProvider(this).get(PlaylistViewModel.class);

        setupRecyclerView();
        observeViewModel();

        fabCreatePlaylist.setOnClickListener(v -> showCreatePlaylistDialog());
    }

    private void setupRecyclerView() {
        recyclerViewPlaylists.setLayoutManager(new LinearLayoutManager(this));
        // 添加分割线
        recyclerViewPlaylists.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        adapter = new PlaylistManagementAdapter(
                playlistInfo -> { // OnPlaylistManageClickListener (点击整个歌单项)
                    if (playlistInfo.id == Constants.FAVORITES_PLAYLIST_ID) {
                        startActivity(new Intent(this, FavoritesActivity.class));
                    } else {
                        Intent intent = new Intent(this, PlaylistSongsActivity.class);
                        intent.putExtra(PlaylistSongsActivity.EXTRA_PLAYLIST_ID, playlistInfo.id);
                        intent.putExtra(PlaylistSongsActivity.EXTRA_PLAYLIST_NAME, playlistInfo.name);
                        intent.putExtra(PlaylistSongsActivity.EXTRA_PLAYLIST_COVER_URI, playlistInfo.displayCoverArtUri);
                        startActivity(intent);
                    }
                },
                (playlistInfo, anchorView) -> { // OnPlaylistOptionsClickListener (点击更多操作按钮)
                    if (playlistInfo.playlistType == PlaylistInfo.TYPE_NORMAL_PLAYLIST) { // 只为普通歌单显示编辑/删除
                        showPlaylistOptionsPopupMenu(playlistInfo, anchorView);
                    } else {
                        Toast.makeText(this, "此歌单不支持更多操作", Toast.LENGTH_SHORT).show();
                    }
                }
        );
        recyclerViewPlaylists.setAdapter(adapter);
    }

    private void observeViewModel() {
        // 观察 PlaylistViewModel 中用于首页的 userPlaylistsToDisplay (只包含用户创建的歌单)
        // 或者，如果 PlaylistViewModel 有一个专门的 getAllUserCreatedPlaylistsInfo() 方法更好
        playlistViewModel.userPlaylistsToDisplay.observe(this, playlistInfos -> {
            Timber.d("PlaylistManagement: User playlists updated, count: %d", playlistInfos != null ? playlistInfos.size() : 0);
            if (playlistInfos != null && !playlistInfos.isEmpty()) {
                // 这里也需要转换 PlaylistInfo，或者 PlaylistManagementAdapter 直接使用 PlaylistInfo
                // 你提供的 PlaylistManagementAdapter 是基于 PlaylistInfo 的，所以这里可以直接使用
                adapter.submitList(new ArrayList<>(playlistInfos));
                tvEmptyPlaylists.setVisibility(View.GONE);
                recyclerViewPlaylists.setVisibility(View.VISIBLE);
            } else {
                adapter.submitList(new ArrayList<>());
                tvEmptyPlaylists.setText("还没有创建歌单，点击右下角按钮创建一个吧！");
                tvEmptyPlaylists.setVisibility(View.VISIBLE);
                recyclerViewPlaylists.setVisibility(View.GONE);
            }
        });

        // 观察歌单创建结果
        playlistViewModel.createdPlaylistId.observe(this, newPlaylistId -> {
            if (newPlaylistId != null && newPlaylistId > 0) {
                Toast.makeText(this, "歌单创建成功!", Toast.LENGTH_SHORT).show();
            } else if (newPlaylistId != null && newPlaylistId == -1L) {
                // 错误信息应由 playlistViewModel.errorMessage 处理
            }
        });
        playlistViewModel.errorMessage.observe(this, error -> {
            if (error != null && !error.isEmpty()) {
                Toast.makeText(this, error, Toast.LENGTH_LONG).show();
            }
        });
        // 观察 isLoading 可以在FAB点击后显示加载状态 (如果需要)
    }

    /**
     * 显示创建新歌单的对话框。
     */
    private void showCreatePlaylistDialog() {
        if (getContext() == null) return;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_create_edit_playlist, null);
        builder.setView(dialogView);

        final TextInputLayout tilPlaylistName = dialogView.findViewById(R.id.textInputLayout_playlist_name_dialog);
        final EditText etPlaylistName = dialogView.findViewById(R.id.editText_playlist_name_dialog);
        final TextInputLayout tilPlaylistDesc = dialogView.findViewById(R.id.textInputLayout_playlist_desc_dialog);
        final EditText etPlaylistDesc = dialogView.findViewById(R.id.editText_playlist_desc_dialog);

        builder.setTitle(R.string.playlist_dialog_title_create); // "新建歌单"

        builder.setPositiveButton(R.string.playlist_create_button_text, (dialog, which) -> { // "创建"
            String name = etPlaylistName.getText().toString().trim();
            String description = etPlaylistDesc.getText().toString().trim();

            if (name.isEmpty()) {
                if (tilPlaylistName != null) tilPlaylistName.setError("歌单名称不能为空");
                Toast.makeText(this, "歌单名称不能为空", Toast.LENGTH_SHORT).show();
                // 此处对话框会自动关闭，若想阻止，需要更复杂处理
                return;
            }
            if (tilPlaylistName != null) tilPlaylistName.setError(null);

            playlistViewModel.createPlaylist(name, description);
        });
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.cancel());
        builder.show();
    }

    /**
     * 显示编辑歌单的对话框。
     *
     * @param playlistToEdit 如果是编辑模式，则传入要编辑的歌单 PlaylistInfo；如果是创建，则传入null。
     */
    private void showEditPlaylistDialog(@Nullable final PlaylistInfo playlistToEdit) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_create_edit_playlist, null); // 复用布局
        builder.setView(dialogView);

        final TextInputLayout tilPlaylistName = dialogView.findViewById(R.id.textInputLayout_playlist_name_dialog);
        final EditText etPlaylistName = dialogView.findViewById(R.id.editText_playlist_name_dialog);
        final TextInputLayout tilPlaylistDesc = dialogView.findViewById(R.id.textInputLayout_playlist_desc_dialog);
        final EditText etPlaylistDesc = dialogView.findViewById(R.id.editText_playlist_desc_dialog);

        builder.setTitle("编辑歌单信息");
        etPlaylistName.setText(playlistToEdit.getName());
        etPlaylistDesc.setText(playlistToEdit.getDescription() != null ? playlistToEdit.getDescription() : "");

        builder.setPositiveButton("保存", (dialog, which) -> {
            String newName = etPlaylistName.getText().toString().trim();
            String newDescription = etPlaylistDesc.getText().toString().trim();

            if (newName.isEmpty()) {
                tilPlaylistName.setError("歌单名称不能为空");
                Toast.makeText(this, "歌单名称不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            tilPlaylistName.setError(null);

            // 更新 Playlist 对象
            playlistToEdit.setName(newName);
            playlistToEdit.setDescription(newDescription);
            // 注意：其他字段如 songCount, creationDate, coverArtUri 不需要在这里修改，它们由其他逻辑管理
            playlistViewModel.updatePlaylist(playlistToEdit);
            Toast.makeText(this, "歌单信息已更新", Toast.LENGTH_SHORT).show();
            // Toolbar 标题会在 getPlaylistDetails LiveData 更新时自动刷新 (通过 observeViewModel)
        });
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.cancel());
        builder.show();
    }

    /**
     * 显示歌单的更多操作选项（编辑、删除）。
     *
     * @param playlistInfo 被操作的歌单信息。
     * @param anchorView   PopupMenu 的锚点视图。
     */
    private void showPlaylistOptionsPopupMenu(final PlaylistInfo playlistInfo, View anchorView) {
        PopupMenu popup = new PopupMenu(this, anchorView);
        popup.getMenuInflater().inflate(R.menu.playlist_management_item_menu, popup.getMenu()); // 需要创建此菜单

        popup.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.action_playlist_manage_edit) {
                showEditPlaylistDialog(playlistInfo); // 传入要编辑的歌单信息
                return true;
            } else if (itemId == R.id.action_playlist_manage_delete) {
                showDeletePlaylistConfirmationDialog(playlistInfo); // 传入要删除的歌单信息
                return true;
            }
            return false;
        });
        popup.show();
    }

    /**
     * 显示删除歌单的确认对话框。
     *
     * @param playlistInfoToDelete 要删除的歌单信息。
     */
    private void showDeletePlaylistConfirmationDialog(final PlaylistInfo playlistInfoToDelete) {
        new AlertDialog.Builder(this)
                .setTitle("删除歌单")
                .setMessage("确定要删除歌单 “" + playlistInfoToDelete.getName() + "” 吗？此操作不可撤销，歌单内的歌曲不会被删除。")
                .setPositiveButton(R.string.ok, (dialog, which) -> {
                    if (playlistViewModel != null) {
                        playlistViewModel.deletePlaylist(playlistInfoToDelete);
                        Toast.makeText(this, "歌单 “" + playlistInfoToDelete.getName() + "” 已删除", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // Toolbar返回按钮，关闭当前Activity
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}